﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net;
using System.Text.RegularExpressions;
using System.Configuration;

namespace Wjtour.Common
{
    public static class Utility
    {
        public static void SendMail(List<string> toEmails, string title, string content)
        {
            SmtpMail mail = new SmtpMail();
            mail.From = ConfigurationManager.AppSettings["SenderMail"];
            mail.FromName = ConfigurationManager.AppSettings["Sender"];
            mail.Body = content;
            mail.Subject = title;
            mail.MailDomainServer = ConfigurationManager.AppSettings["MailDomainServer"];
            mail.MailDomainPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailDomainPort"]);
            mail.MailServerUserName = ConfigurationManager.AppSettings["MailServerUserName"];
            mail.MailServerPassWord = ConfigurationManager.AppSettings["MailServerPassWord"];
            mail.Html = true;
            mail.AddRecipient(toEmails);
            mail.Send();
        }

        public static void SendMail(string email, string title, string content)
        {
            List<string> toEmails = new List<string>();
            toEmails.Add(email);
            SmtpMail mail = new SmtpMail();
            mail.From = ConfigurationManager.AppSettings["SenderMail"];
            mail.FromName = ConfigurationManager.AppSettings["Sender"];
            mail.Body = content;
            mail.Subject = title;
            mail.MailDomainServer = ConfigurationManager.AppSettings["MailDomainServer"];
            mail.MailDomainPort = Convert.ToInt32(ConfigurationManager.AppSettings["MailDomainPort"]);
            mail.MailServerUserName = ConfigurationManager.AppSettings["MailServerUserName"];
            mail.MailServerPassWord = ConfigurationManager.AppSettings["MailServerPassWord"];
            mail.Html = true;
            mail.AddRecipient(toEmails);
            bool b = mail.Send();
        }

        /// <summary>
        /// 页数从1开始
        /// </summary>
        /// <param name="url"></param>
        /// <param name="currentpage"></param>
        /// <param name="totalpage"></param>
        /// <returns></returns>
        public static string GetAjaxPageHtml(string url, int currentpage, int totalpage)
        {
            int prepage = currentpage <= 1 ? 1 : currentpage - 1;
            int nextpage = totalpage > currentpage + 1 ? currentpage + 1 : totalpage;
            string thispageUrl = url.IndexOf("?") > -1 ? url + "&page=" + currentpage : url + "?page=" + currentpage;
            string prepageUrl = url.IndexOf("?") > -1 ? url + "&page=" + prepage : url + "?page=" + prepage;
            string nextpageUrl = url.IndexOf("?") > -1 ? url + "&page=" + nextpage : url + "?page=" + nextpage;
            string endpageUrl = url.IndexOf("?") > -1 ? url + "&page=" + totalpage : url + "?page=" + totalpage;

            int startpage = currentpage;
            int endpage = Math.Min(currentpage + 2, totalpage);
            startpage = Math.Max(endpage - 2, 1);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<span class=\"pagecount\">共" + totalpage + "页</span>");
            sb.AppendLine("<a href=\"#\" data-url=\"" + url + "\"><span class=\"home\">首页</span></a>");
            sb.AppendLine("<a href=\"#\" data-url=\"" + prepageUrl + "\"><span class=\"prepage\">上一页</span></a>");
            for (int i = startpage; i <= endpage; i++)
            {
                if (i == currentpage)
                {
                    sb.AppendLine("<a href=\"#\" data-url=\"" + thispageUrl + "\"><span class=\"thispage\">" + currentpage + "</span></a>");
                }
                else
                {
                    string pageUrl = url.IndexOf("?") > -1 ? url + "&page=" + i : url + "?page=" + i;
                    sb.AppendLine("<a href=\"#\" data-url=\"" + pageUrl + "\"><span class=\"pagenum\">" + i + "</span></a>");
                }
            }
            sb.AppendLine("<a href=\"#\" data-url=\"" + nextpageUrl + "\"><span class=\"nextpage\">下一页</span></a>");
            sb.AppendLine("<a href=\"#\" data-url=\"" + endpageUrl + "\"><span class=\"endpage\">末页</span></a>");

            return sb.ToString();
        }

        /// <summary>
        /// 根据等级获取景区‘A’的个数的html
        /// </summary>
        /// <param name="rank"></param>
        /// <returns></returns>
        public static string GetAHtml(int rank)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rank; i++)
            {
                sb.Append("A");
            }
            return sb.ToString();
        }
        /// <summary>
        /// 根据酒店星级获取对应的html
        /// </summary>
        /// <param name="star"></param>
        /// <returns></returns>
        public static string GetStarHtml(int star)
        {
            StringBuilder sb = new StringBuilder();
            var end = Math.Min(5, star);
            for (int i = 0; i < end; i++)
            {
                sb.Append("<img src=\"/css/images/icon12.png\" />");
            }
            if (end < 5)
            {
                for (int i = end; i < 5; i++)
                {
                    sb.Append("<img src=\"/css/images/icon13.png\" />");
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 去掉html tags
        /// </summary>
        /// <param name="sourceHtml"></param>
        /// <returns></returns>
        public static string StripHtml(string sourceHtml)
        {
            string s = Regex.Replace(sourceHtml, "<[^>]*(>|$)", string.Empty);
            return WebUtility.HtmlDecode(Regex.Replace(s, @"\s", string.Empty));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="omit">是否加省略号</param>
        /// <returns></returns>
        public static string CutString(string str, int length, bool omit)
        {
            if (string.IsNullOrEmpty(str)) return string.Empty;
            if (str.Length <= length) return str;
            return str.Substring(0, length) + (omit ? "..." : "");
        }
        //定义函数pageft(),三个参数的含义为：
        //totalPage：信息总数；
        //pagesize：每页显示信息数，这里设置为默认是20；
        //url：分页导航中的链接，除了加入不同的查询信息“page”外的部分都与这个URL相同。
        //　　　默认值本该设为本页URL（即_SERVER["REQUEST_URI"]），但设置默认值的右边只能为常量，所以该默认值设为空字符串，在函数内部再设置为本页URL。
        public static string pageft(int totalPage, string url = "", int pagesize = 20, int wjt = 0, int shownum = 1, int showtext = 1, int showselect = 0, int showlvtao = 7, int admin = 0)
        {
            if (admin == 1)
            {
                showselect = 1;
            }
            int page = 1;
            if (!string.IsNullOrEmpty(HttpContext.Current.Request["page"]))
                page = Hjp.FrameWork.Common.Utils.StrToInt(HttpContext.Current.Request["page"], 0);

            if (wjt == 0)
            {
                url += "&page";
            }
            else if (wjt == 1)
            {
                url = url.Replace(".html", "");
            }

            //页码计算：
            int lastpg = (int)Math.Ceiling((double)totalPage / (double)pagesize); //最后页，也是总页数
            page = Math.Min(lastpg, page);
            int prepg = page > 1 ? page - 1 : 1; //上一页
            int nextpg = (page == lastpg ? lastpg : page + 1); //下一页
            int firstcount = (page - 1) * pagesize;
            string pagenav = string.Empty;

            //开始分页导航条代码：
            if (showtext == 1)
            {
                pagenav = "<span class='disabled'>" + (totalPage > 0 ? (firstcount + 1) : 0) + "-" + Math.Min(firstcount + pagesize, totalPage) + "/" + totalPage + " 记录</span><span class='disabled'>" + page + "/" + lastpg + " 页</span>";
            }
            else
            {
                pagenav = "";
            }

            //如果只有一页则跳出函数：
            if (lastpg <= 1)
                return string.Empty;

            if (wjt == 1)
            {
                if (prepg > 0)
                    pagenav += "<a href='" + url + "-1.html'>首页</a>";
                else
                    pagenav += "<a href='" + url + "-1.html'>首页</a>";
                if (prepg > 0)
                    pagenav += "<a href='" + url + "-" + prepg + ".html'><</a>";
                else
                    pagenav += "<a href='" + url + "-" + prepg + ".html'><</a>";
            }
            else
            {
                if (prepg > 0)
                    pagenav += "<a href='" + url + "=1'>首页</a>";
                else
                    pagenav += "<a href='" + url + "=1'>首页</a>";
                if (prepg > 0)
                    pagenav += "<a href='" + url + "=" + prepg + "'><</a>";
                else
                    pagenav += "<a href='" + url + "=" + prepg + "'><</a>";
            }
            if (shownum == 1)
            {
                int o = showlvtao; //中间页码表总长度，为奇数
                int u = (int)Math.Ceiling((double)(o / 2)); //根据o计算单侧页码宽度u
                int f = page - u; //根据当前页currentPage和单侧宽度u计算出第一页的起始数字
                //str_replace('{p}',,fn)//替换格式
                if (f < 0)
                {
                    f = 0;
                } //当第一页小于0时，赋值为0
                int n = lastpg; //总页数,20页
                if (n < 1)
                {
                    n = 1;
                } //当总数小于1时，赋值为1
                if (page == 1)
                {
                    pagenav += "<span class=\"current\">1</span>";
                }
                else
                {
                    if (wjt == 1)
                    {
                        pagenav += "<a href='" + url + "-1.html'>1</a>";
                    }
                    else
                    {
                        pagenav += "<a href='" + url + "=1'>1</a>";
                    }
                }
                ///////////////////////////////////////
                for (int i = 1; i <= o; i++)
                {
                    if (n <= 1)
                    {
                        break;
                    } //当总页数为1时
                    int c = f + i; //从第c开始累加计算
                    if (i == 1 && c > 2)
                    {
                        pagenav += "...";
                    }
                    if (c == 1)
                    {
                        continue;
                    }
                    if (c == n)
                    {
                        break;
                    }
                    if (c == page)
                    {
                        pagenav += "<span class=\"current\">" + page + "</span>";
                    }
                    else
                    {
                        if (wjt == 1)
                        {
                            pagenav += "<a href='" + url + "-" + c + ".html'>c</a>";
                        }
                        else
                        {
                            pagenav += "<a href='" + url + "=" + c + "'>" + c + "</a>";
                        }
                    }
                    if (i == o && c < n - 1)
                    {
                        pagenav += "...";
                    }
                    if (i > n)
                    {
                        break;
                    } //当总页数小于页码表长度时	
                }
                if (page == n && n != 1)
                {
                    pagenav += "<span class=\"current\">" + n + "</span>";
                }
                else
                {
                    if (wjt == 1)
                    {
                        pagenav += "<a href='" + url + "-" + n + ".html'>" + n + "</a>";
                    }
                    else
                    {
                        pagenav += "<a href='" + url + "=" + n + "'>" + n + "</a>";
                    }
                }
            }

            if (wjt == 1)
            {
                if (nextpg > 0)
                    pagenav += "<a href='" + url + "-" + nextpg + ".html'>></a>";
                else
                    pagenav += "<a href='" + url + "-" + nextpg + ".html'>></a>";
                if (nextpg > 0)
                    pagenav += "<a href='" + url + "-" + lastpg + ".html'>尾页</a>";
                else
                    pagenav += "<a href='" + url + "-" + lastpg + ".html'>尾页</a>";
                ;
            }
            else
            {
                if (nextpg > 0)
                    pagenav += "<a href='" + url + "=" + nextpg + "'>></a>";
                else
                    pagenav += "<a href='" + url + "=" + nextpg + "'>></a>";
                if (nextpg > 0)
                    pagenav += "<a href='" + url + "=" + lastpg + "'>尾页</a>";
                else
                    pagenav += "<a href='" + url + "=" + lastpg + "'>尾页</a>";
                ;
            }
            if (showselect == 1)
            {
                //下拉跳转列表，循环列出所有页码：
                pagenav += "跳至<select name='topage' size='1' onchange='window.location=\"" + url + "=\"+this.value'>\n";
                for (int i = 1; i <= lastpg; i++)
                {
                    if (i == page)
                        pagenav += "<option value='i' selected>" + i + "</option>\n";
                    else
                        pagenav += "<option value='i'>" + i + "</option>\n";
                }
                pagenav += "</select>页";
            }
            return pagenav;
        }
        public static string GetSafeSql(string value)
        {
            return value.Replace("'", "''");
        }

        /// <summary>
        /// 将Unix时间戳转换为DateTime类型时间
        /// </summary>
        /// <param name="d">double 型数字</param>
        /// <returns>DateTime</returns>
        public static System.DateTime ConvertIntDateTime(long d)
        {
            System.DateTime time = System.DateTime.MinValue;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            time = startTime.AddSeconds(d);
            return time;
        }

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>double</returns>
        public static long ConvertDateTimeInt(System.DateTime time)
        {
            long intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (long)(time - startTime).TotalSeconds;
            return intResult;
        }

        #region 固定模版裁剪并缩放
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <remarks> 2010-11-15</remarks>
        /// <param name="postedFile">原图HttpPostedFile对象</param>
        /// <param name="fileSaveUrl">保存路径</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量（范围0-100）</param>
        public static void CutForCustom(System.Web.HttpPostedFile postedFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片，并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

            //原图宽高均小于模版，不作处理，直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原图与模版比例相等，直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原图与模版比例不等，裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0);//原图裁剪定位
                    Rectangle toR = new Rectangle(0, 0, 0, 0);//目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate));
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X = 0;
                        fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width = initImage.Width;
                        fromR.Height = (int)Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = initImage.Width;
                        toR.Height = (int)Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y = 0;
                        fromR.Width = (int)Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = (int)Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //关键质量控制
                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo ici = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存缩略图
                    //templateImage.Save(fileSaveUrl, ici, ep);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //释放资源
            initImage.Dispose();
        }
        #endregion

        /// <summary>
        /// 网站前台幻灯片位置
        /// </summary>
        public static Dictionary<int, string> Slides
        {
            get
            {
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(1, "首页顶部幻灯片");
                dic.Add(2, "首页美图欣赏幻灯片");
                dic.Add(3, "景区景点幻灯片");
                dic.Add(4, "景区门票幻灯片");
                dic.Add(5, "酒店住宿幻灯片");
                return dic;
            }
        }
    }
}